# coding=utf-8
from model import AGENT_PAY_STATUS
from .db import create_agent_pay_order, get_agent_pay_order
from common.utils.exceptions import ParamError
from datetime import datetime


class AbstractHandler(object):

    def submit_order(self, order_no):
        raise NotImplementedError()

    def create_agent_pay(self, operator_id, channel_id, total_fee, bankcard):
        """
        创建代付请求
        :return:
        """
        agent_pay_order = create_agent_pay_order(operator_id, channel_id, total_fee, bankcard)
        out_order_no, notify_url, log = self.submit_order(agent_pay_order.order_no)
        if out_order_no:
            agent_pay_order.notify_url = notify_url
            agent_pay_order.status = AGENT_PAY_STATUS.SUBMIT
            agent_pay_order.out_order_no = out_order_no

            agent_pay_order.save()
        return log

    def query_agent_pay(self, order_no):
        """
        查询代付请求
        :return:
        """
        raise NotImplementedError()

    def agent_pay_callback(self, order_no, status):
        """
        代付到账回调
        :return:
        """
        assert status in (AGENT_PAY_STATUS.SUCCESS, AGENT_PAY_STATUS.FAIL)
        order = get_agent_pay_order(order_no, True)
        if order.status != AGENT_PAY_STATUS.SUBMIT:
            raise ParamError('agent_pay_callback status error {}'.format(order.status))

        order.status = status
        order.notified_at = datetime.utcnow()
        order.save()
